
#include <stdlib.h>

#include "ch.h"
#include "hal.h"

#include "chprintf.h"
#include "remote.h"
#include "myNRF24.h"

static VirtualTimer vt;

/* LED set to OFF after 200mS.*/
static void ledoff(void *arg) {

  (void)arg;
  //palSetPad(GPIOA, GPIOA_LED);
}

/* Triggered when the button is pressed or released. The LED is set to ON.*/
static void extcb1(EXTDriver *extp, expchannel_t channel) {

  (void)extp;
  (void)channel;
  //palClearPad(GPIOA, GPIOA_LED);
  chSysLockFromIsr();
	remoteSendEvtI(1);
  if (!chVTIsArmedI(&vt))
    chVTSetI(&vt, MS2ST(200), ledoff, NULL);
  chSysUnlockFromIsr();
}

/* Triggered when the LED goes OFF.*/
static void extcb2(EXTDriver *extp, expchannel_t channel) {

  (void)extp;
  (void)channel;
}

/* Triggered by NRF24 */
static void extcb3(EXTDriver *extp, expchannel_t channel) {

  (void)extp;
  (void)channel;
	chSysLockFromIsr();
	NRFReportIRQ();
  chSysUnlockFromIsr();

}


static const EXTConfig extcfg = {  
	{
    {EXT_CH_MODE_DISABLED, NULL},
    {EXT_CH_MODE_DISABLED, NULL},
		{EXT_CH_MODE_DISABLED, NULL},
		{EXT_CH_MODE_BOTH_EDGES | EXT_CH_MODE_AUTOSTART | EXT_MODE_GPIOA, extcb1},
    {EXT_CH_MODE_DISABLED, NULL},
		{EXT_CH_MODE_RISING_EDGE | EXT_CH_MODE_AUTOSTART | EXT_MODE_GPIOA, extcb2},
    {EXT_CH_MODE_DISABLED, NULL},
    {EXT_CH_MODE_DISABLED, NULL},
    {EXT_CH_MODE_DISABLED, NULL},
    {EXT_CH_MODE_DISABLED, NULL},
    {EXT_CH_MODE_DISABLED, NULL},
    {EXT_CH_MODE_DISABLED, NULL},
    {EXT_CH_MODE_DISABLED, NULL},
    {EXT_CH_MODE_DISABLED, NULL},
    {EXT_CH_MODE_DISABLED, NULL},
    {EXT_CH_MODE_RISING_EDGE | EXT_CH_MODE_AUTOSTART | EXT_MODE_GPIOA, extcb3}
  }
};

void initExt(void) {
	/*
   * Activates the EXT driver 1.
   */
  extStart(&EXTD1, &extcfg);
}
